<template>
	<div class="table-box">
		<ProTable
			ref="proTable"
			title="用户列表"
			:columns="columns"
			:requestApi="getTableList"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增用户</el-button>
				<el-button type="primary" :icon="Upload" plain @click="batchAdd">批量添加用户</el-button>
				<el-button type="primary" :icon="Download" plain @click="downloadFile">导出用户数据</el-button>
				<el-button type="danger" :icon="Delete" plain @click="batchDelete(scope.selectedListIds)" :disabled="!scope.isSelected">
					批量删除用户
				</el-button>
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
				<el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
				<el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
			</template>
		</ProTable>
		<UserDrawer ref="drawerRef" />
		<ImportExcel ref="dialogRef" />
	</div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { ElMessageBox } from "element-plus";
import { User } from "@/api/interface";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/manageUser/components/UserDrawer.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View } from "@element-plus/icons-vue";
import {
	getUserList,
	deleteUser,
	editUser,
	addUser,
	changeUserStatus,
	exportUserInfo,
	BatchAddUser,
	getUserStatus
} from "@/api/modules/user";
import { IMap, IArr, IUserMap } from "@/views/interface/index";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	type: 1
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	// 角色字典
	const roleMap: IMap<string> = {
		student: "学生",
		teacher: "老师",
		visitor: "校外来访人员",
		staff: "校内职工",
		security: "安保人员",
		driver: "校车司机"
	};
	// 权限字典
	const perArr: IArr<string> = ["普通用户", "保安", "普通管理员", "系统管理员"];

	data.userList.forEach((item: IUserMap) => {
		item.role = roleMap[item.role];
		item.perid = perArr[item.perid];
	});
	console.log("userList", data.userList);
	return {
		datalist: data.userList,
		total: data.total,
		pageNum: data.pageNum,
		pageSize: data.pageSize
	};
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	let newParams = { ...params };
	newParams.username && (newParams.username = "custom-" + newParams.username);
	return getUserList(newParams);
};

// 表格配置项
const columns: ColumnProps[] = [
	{ type: "selection", fixed: "left", width: 40 },
	{ type: "index", label: "#", width: 50 },
	{
		prop: "uid",
		label: "学号/工号",
		width: 100,
		search: { el: "input" }
	},
	{
		prop: "username",
		label: "姓名",
		search: { el: "input" }
	},
	{
		prop: "role",
		label: "角色",
		search: { el: "select" },
		fieldNames: { label: "roleLabel", value: "roleValue" }
	},
	{
		prop: "mobile",
		label: "电话号码",
		width: 100,
		search: { el: "input" }
	},
	{ prop: "mail", label: "邮箱" },
	{ prop: "perid", label: "权限级别", width: 100 },
	{ prop: "carnumber", label: "车牌", search: { el: "input" } },
	{
		prop: "status",
		label: "用户状态",
		width: 120,
		enum: getUserStatus,
		fieldNames: { label: "userLabel", value: "userStatus" },
		search: {
			el: "tree-select",
			props: { props: { label: "userLabel" }, nodeKey: "userStatus" }
		},
		render: (scope: { row: User.ResUserList }) => {
			return (
				<>
					{1 < 2 ? (
						<el-switch
							model-value={scope.row.status}
							active-text={scope.row.status ? "启用" : "禁用"}
							active-value={1}
							inactive-value={0}
							onClick={() => changeStatus(scope.row)}
						/>
					) : (
						<el-tag type={scope.row.status ? "success" : "danger"}>{scope.row.status ? "启用" : "禁用"}</el-tag>
					)}
				</>
			);
		}
	},
	{ prop: "operation", label: "操作", fixed: "right", width: 230 }
];

// 删除用户信息
const deleteAccount = async (params: User.ResUserList) => {
	await useHandleData(deleteUser, { id: [params.id] }, `删除【${params.username}】用户`);
	proTable.value.getTableList();
};

// 批量删除用户信息
const batchDelete = async (id: string[]) => {
	await useHandleData(deleteUser, { id }, "删除所选用户信息");
	proTable.value.clearSelection();
	proTable.value.getTableList();
};

// 切换用户状态
const changeStatus = async (row: User.ResUserList) => {
	await useHandleData(changeUserStatus, { id: row.id, status: row.status == 1 ? 0 : 1 }, `切换【${row.username}】用户状态`);
	proTable.value.getTableList();
};

// 导出用户列表
const downloadFile = async () => {
	ElMessageBox.confirm("确认导出用户数据?", "温馨提示", { type: "warning" }).then(() =>
		useDownload(exportUserInfo, "用户列表", proTable.value.searchParam)
	);
};

// 批量添加用户
const dialogRef = ref();
const batchAdd = () => {
	let params = {
		title: "用户",
		tempApi: exportUserInfo,
		importApi: BatchAddUser,
		getTableList: proTable.value.getTableList
	};
	dialogRef.value.acceptParams(params);
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string, rowData: Partial<User.ResUserList> = {}) => {
	let params = {
		title,
		rowData: { ...rowData },
		isView: title === "查看",
		api: title === "新增" ? addUser : title === "编辑" ? editUser : "",
		getTableList: proTable.value.getTableList
	};
	drawerRef.value.acceptParams(params);
};
</script>
